﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Adams.Web.Logic.Security
{
    public class PasswordReset
    {
        public static Models.Security.PasswordReset.PageLoad PageLoad(string code)
        {
            var ret = new Models.Security.PasswordReset.PageLoad();
            ret.Code = code;
            return ret;
        }

        public static Models.FormOutput TryPasswordReset(Models.Security.PasswordReset.FormInput input)
        {
            var output = Validation.PerformBasicValidation(input);

            if (output.IsValid)
            {
                if (!Shared.Str.IsEqual(input.Password1, input.Password2))
                {
                    output.InvalidFields.Add(new Models.InvalidField() { Name = "Password2", Code = 6 });
                }

                if (output.IsValid)
                {
                    string email = Logic.Email.GetEmailFromCode(input.Code);
                    var data = Data.Security.Common.GetMemberInfo(email);
                    string hashedPassword = Adams.Shared.Encryption.HashPassword(input.Password1, data.PasswordSalt);
                    Data.Security.PasswordReset.ResetPassword(email, hashedPassword);
                    output.IsSaved = true;

                    string subject = "Your password has been reset";
                    string from = Shared.Config.GetAppSetting("SecurityFromEmail");
                    string body = Logic.Email.GeneratePasswordResetCompleteEmail(email);
                    Email.QueueEmail(subject, from, email, body, 1);
                }
            }

            return output;
        }
    }
}
